package com.bob.light

import android.content.Context
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.Checkable
import android.widget.EditText
import android.widget.Toast
import com.bob.light.config.AppConfig

fun Any.toast(context: Context = AppConfig.application(), duration: Int = Toast.LENGTH_SHORT) {
    Toast.makeText(context, this.toString(), duration).apply { show() }
}

inline fun <T: View> T.setOnSingleClickListener(time: Long = 500, crossinline block: (T) -> Unit) {
    setOnClickListener {
        val currentTimeMillis = System.currentTimeMillis()
        if (currentTimeMillis - lastClickTime > time || this is Checkable) {
            lastClickTime = currentTimeMillis
            block(this)
        }
    }
}
//兼容点击事件设置为this的情况
fun <T: View> T.setOnSingleClickListener(onClickListener: View.OnClickListener, time: Long = 500) {
    setOnClickListener {
        val currentTimeMillis = System.currentTimeMillis()
        if (currentTimeMillis - lastClickTime > time || this is Checkable) {
            lastClickTime = currentTimeMillis
            onClickListener.onClick(this)
        }
    }
}

var <T : View> T.lastClickTime: Long
    set(value) = setTag(1766613352, value)
    get() = getTag(1766613352) as? Long ?: 0

fun View.isVisibilityOrGone(visible: Boolean) {
    if (visible) {
        this.visibility = View.VISIBLE
    } else {
        this.visibility = View.GONE
    }
}
fun View.isVisibilityOrInvisible(visible: Boolean) {
    if (visible) {
        this.visibility = View.VISIBLE
    } else {
        this.visibility = View.INVISIBLE
    }
}

fun EditText.addTextChangedSampleListener(block: (s: CharSequence?) -> Unit): TextWatcher {
    val tempListener = object : TextWatcher {
        override fun afterTextChanged(s: Editable?) {
            block(s)
        }
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
    }
    this.addTextChangedListener(tempListener)
    return tempListener
}